import re
import json
import ubinascii
import machine
import gc

config_file = open("./config.json", "r")
config = json.loads(config_file.read())
print(config)


def get_config(key):
    if key in config:
        return config[key]
    return None


def get_device_id():
    """获取设备ID"""
    return ubinascii.hexlify(machine.unique_id()).decode("utf-8")


def get_device_info():
    """获取设备信息"""
    return get_config("device_info")


def string_to_hex(s):
    return s.encode("utf-8").hex()


def transformPayload(payload):
    return bytes.fromhex(string_to_hex(payload))


def transformResponse(response):
    """处理HTTP RESPONSE"""
    print_gc_info()
    resp = response.decode()
    resp = re.sub(r"\+IPD,\d+:", "", resp)
    # print(resp)
    match = re.search(r"\{(.*?)CLOSED", resp)
    if match:
        json_str = "{" + match.group(1)
        data = json.loads(json_str)
        print_gc_info()
        return data
    return ""


def print_gc_info():
    free_m = gc.mem_free()
    alloc_m = gc.mem_alloc()
    print("free: ", free_m / 1024, "KB alloc_m: ", alloc_m / 1024, "KB")
    
def collect_gc_info():
    gc.collect()
    free_m = gc.mem_free()
    alloc_m = gc.mem_alloc()
    print("free: ", free_m / 1024, "KB alloc_m: ", alloc_m / 1024, "KB")


def format_network_response(resp):
    if "Codemao_0" in resp:
        return {}
    return resp


def url_escape(s):
    return "".join(c if c.isalpha() or c.isdigit() else "%%%02x" % ord(c) for c in s)


def decode_base64(base64_str):
    return ubinascii.a2b_base64(base64_str)

